<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="合同名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入合同名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="checkStatus">
        <el-select v-model="queryParams.checkStatus" placeholder="请选择审核状态" clearable size="small">
          <el-option
            v-for="dict in checkStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下单日期">
        <el-date-picker
          v-model="daterangeOrderDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="负责人" prop="ownerUserName">
        <el-input
          v-model="queryParams.ownerUserName"
          placeholder="请输入负责人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司签约人" prop="companyUserName">
        <el-input
          v-model="queryParams.companyUserName"
          placeholder="请输入公司签约人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:contract:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:contract:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:contract:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" align="center" prop="num" />
      <el-table-column label="合同名称" align="center" prop="name">
        <template slot-scope="scope">
          <el-link @click="showDetail(scope.row)" style="color:#1890ff">{{scope.row.name}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="customerName" />
      <el-table-column label="商机名称" align="center" prop="businessName" />
      <el-table-column label="下单日期" align="center" prop="orderDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="ownerUserName" />
      <el-table-column label="产品总金额(元)" align="center" prop="totalPrice" />
      <el-table-column label="整单折扣(%)" align="center" prop="discountRate" />
      <el-table-column label="合同金额(元)" align="center" prop="money" />
      <el-table-column label="客户签约人" align="center" prop="contacts" />
      <el-table-column label="公司签约人" align="center" prop="companyUserName" />
      <el-table-column label="审核状态" align="center" prop="checkStatus" :formatter="checkStatusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.checkStatus != 1 && scope.row.checkStatus != 3"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:contract:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.checkStatus != 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:contract:remove']"
          >删除</el-button>
          <el-button
            v-if="scope.row.checkStatus == 2 || scope.row.checkStatus == 0"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="submitCheckStatus(scope.row)"
          >提交审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="contractDownload(scope.row)"
          >合同下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="num">
              <el-input v-model="form.num" placeholder="请输入合同编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-input v-model="form.customerName" readonly placeholder="请选择商机" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商机" prop="businessId">
              <el-input placeholder="请选择商机" readonly v-model="form.businessName">
                <el-button slot="append" icon="el-icon-search" @click="selCusBus"></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="下单日期" prop="orderDate">
              <el-date-picker clearable size="small"
                v-model="form.orderDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择下单日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公司负责人" prop="ownerUserId">
              <el-select v-model="form.ownerUserId" placeholder="请选择公司负责人" filterable>
                <el-option
                  v-for="dict1 in customerLeaders"
                  :key="dict1.userId"
                  :label="dict1.nickName"
                  :value="dict1.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司签约人" prop="companyUserId">
              <el-select v-model="form.companyUserId" placeholder="请选择公司签约人" filterable>
                <el-option label="请选择公司签约人" value="" />
                <el-option
                  v-for="dict1 in customerLeaders"
                  :key="dict1.userId"
                  :label="dict1.nickName"
                  :value="dict1.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户签约人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入客户签约人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="contactsTel">
              <el-input v-model="form.contactsTel" placeholder="请输入客户签约人电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable size="small"
                v-model="form.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable size="small"
                v-model="form.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同类型" prop="types">
              <el-input v-model="form.types" placeholder="请输入合同类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款方式" prop="paymentType">
              <el-input v-model="form.paymentType" placeholder="请输入付款方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="交货地点" prop="placeDelivery">
          <el-input v-model="form.placeDelivery" placeholder="请输入交货地点" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品总金额" prop="totalPrice">
              <el-input-number v-model="form.totalPrice" readonly controls-position="right" :min="0"/><span style="color:red;"> 选择产品后自动计算</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="整单折扣" prop="discountRate">
              <el-input-number v-model="form.discountRate" controls-position="right" :min="0" @change = "setPrice"/><span style="color:red;"> %</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额" prop="money">
              <el-input-number v-model="form.money" readonly controls-position="right" :min="0"/><span style="color:red;"> 选择产品、折扣后自动计算</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="附件" prop="annex">
          <fileUpload v-model="form.annex"/>
        </el-form-item>
        <contractProduct :businessId = "this.form.id" :type = 2 :busProductList = "this.form.busProductList" @setPrice="setPrice"></contractProduct>
        <el-form-item label="合同模板" prop="template">
          <el-select v-model="form.template" placeholder="请选择合同模板" filterable>
            <el-option
              v-for="dict1 in listConTemplates"
              :key="dict1.templateName"
              :label="dict1.templateName"
              :value="dict1.templateName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>




    <!-- 选择客户对话框 -->
    <el-dialog :title="selCusTitle" :visible.sync="selCusOpen" width="50%" append-to-body>
      <busCustomers @selCusCancel = "selCusCancel" @getCustomerInfo = "getCustomerInfo" :isNewTime = "this.isNewTime"></busCustomers>
    </el-dialog>
    <!-- 选择商机对话框 -->
    <el-dialog :title="conCusTitle" :visible.sync="conCusOpen" width="50%" append-to-body>
      <contractBus @conCusCancel = "conCusCancel" @getSelBusinessInfo = "getSelBusinessInfo" :isNewTime = "this.isNewTime"></contractBus>
    </el-dialog>

    

    <!-- 右侧弹出详情信息 -->
    <el-drawer
      title="合同跟踪"
      :visible.sync="drawer"
      :direction="direction"
      :modal = false
      size = "70%"
      :before-close="handleClose">
      <followUp :businessId='this.form.id'></followUp>
    </el-drawer>

  </div>
</template>

<script>
import { listContract, submitCheckStatus, delContract, addContract, updateContract, exportContract, selectCrmProContractById } from "@/api/crm/contract/contract";
import { contractDownload, listConTemplates } from "@/api/crm/templates/templates";
import contractProduct from '../busProduct/contractProduct';
import busCustomers from '../customer/bus_customers';
import contractBus from '../business/contract_bus';
import { listadmin } from "@/api/system/user";
import FileUpload from '@/components/FileUpload';
import followUp from './followUp'
import { getCrmBusProductById } from "@/api/crm/business/business";

export default {
  name: "Contract",
  components: {
    contractProduct,
    busCustomers,
    contractBus,
    FileUpload,
    followUp
  },
  data() {
    return {
      //右侧弹出层
      drawer: false,
      direction: 'rtl',
      selCusTitle: "",
      selCusOpen: false,
      conCusTitle: "",
      conCusOpen: false,
      customerLeaders: [],
      //获取随机数，每次选择客户都重新刷新查询页面
      isNewTime: new Date(),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同管理表格数据
      contractList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核状态字典
      checkStatusOptions: [],
      // 下单日期时间范围
      daterangeOrderDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        customerId: null,
        checkStatus: null,
        orderDate: null,
        ownerUserId: null,
        companyUserId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        num: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "合同名称不能为空", trigger: "blur" }
        ],
        customerId: [
          { required: true, message: "客户名称不能为空", trigger: "blur" }
        ],
        businessId: [
          { required: true, message: "商机名称不能为空", trigger: "blur" }
        ],
        orderDate: [
          { required: true, message: "下单日期不能为空", trigger: "blur" }
        ],
        ownerUserId: [
          { required: true, message: "公司负责人不能为空", trigger: "blur" }
        ],
      },
      listConTemplates: [],
    };
  },
  created() {
    this.getList();
    this.getDicts("check_status").then(response => {
      this.checkStatusOptions = response.data;
    });
    listadmin().then(response => {
      this.customerLeaders = response.data;
    });
    listConTemplates().then(response => {
      this.listConTemplates = response;
    });
  },
  methods: {
    //右侧弹出层
    showDetail(row){
      this.reset();
      const id = row.id || this.ids
      this.form.id = id;
      this.drawer = true;
    },
    //右侧弹出层关闭
    handleClose(done) {
      this.getList();
//      this.$confirm('确认关闭？')
//       .then(_ => {
          done();
//        }).catch(_ => {});
    },
    /** 选择商品后，合同金额业务处理 */
    setPrice(){
        let contractManey = 0;
        let totalMoney = 0;
        this.form.busProductList.map((item, index) => {
          contractManey = contractManey + item.salesPrice * item.num;
          totalMoney = totalMoney + item.salesPrice * item.num
        })
        this.form.money = contractManey - contractManey * this.form.discountRate / 100;
        this.form.totalPrice = totalMoney;
    },
    //选中客户后处理逻辑
    getCustomerInfo(selection){
      this.form.customerId = selection.id;
      this.form.customerName = selection.customerName;
      this.selCusOpen = false;
    },
    //选中商机后处理逻辑
    getSelBusinessInfo(selection){
      this.form.customerId = selection.customerId;
      this.form.customerName = selection.customerName;
      this.form.businessId = selection.id;
      this.form.businessName = selection.businessName;
      this.form.discountRate = selection.discountRate;

      let params = {id: selection.id, type: 1}
      getCrmBusProductById(params).then(response => {
        if(null != response.data){
          this.form.busProductList = response.data.busProductList;
        }
      });

      this.conCusOpen = false;
    },
    //选择客户对话框取消按钮
    selCusCancel(){
      this.selCusOpen = false;
    },
    //选择商机对话框取消按钮
    conCusCancel(){
      this.conCusOpen = false;
    },
    //选择客户
    selCustomer(){
      this.isNewTime = new Date() + Math.round(Math.random()*50000);
      this.selCusTitle = "选择客户";
      this.selCusOpen = true;
    },
    //选择商机
    selCusBus(){
      this.isNewTime = new Date() + Math.round(Math.random()*50000);
      this.conCusTitle = "选择商机";
      this.conCusOpen = true;
    },
    /** 查询合同管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeOrderDate && '' != this.daterangeOrderDate) {
        this.queryParams.params["beginOrderDate"] = this.daterangeOrderDate[0];
        this.queryParams.params["endOrderDate"] = this.daterangeOrderDate[1];
      }
      listContract(this.queryParams).then(response => {
        this.contractList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //提交审核
    submitCheckStatus(row){
      let _this = this;
      this.$confirm('提交审核后，将不允许修改，确认提交？', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        let params = {id: row.id};
        submitCheckStatus(params).then(response => {
          _this.getList();
          _this.msgSuccess("提交审核成功");
        });
      }).then(() => {
        
      })

      
    },
    // 审核状态字典翻译
    checkStatusFormat(row, column) {
      return this.selectDictLabel(this.checkStatusOptions, row.checkStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        customerId: null,
        businessId: null,
        checkStatus: null,
        examineRecordId: null,
        orderDate: null,
        ownerUserId: null,
        num: null,
        startTime: null,
        endTime: null,
        money: null,
        discountRate: null,
        totalPrice: null,
        types: null,
        paymentType: null,
        batchId: null,
        roUserId: null,
        rwUserId: null,
        contacts: null,
        contactsTel: null,
        companyUserId: null,
        lastTime: null,
        receivedMoney: null,
        unreceivedMoney: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        delFlag: null,
        annex: null,
        busProductList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeOrderDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(row.checkStatus == 1){
        this.$alert("合同已审核通过，不允许修改", "提示", { confirmButtonText: "确定", });
        return;
      }else{
        this.reset();
        const id = row.id || this.ids
        let params = {id: row.id || this.ids, type: 2};
        selectCrmProContractById(params).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改合同";
        });
      }
      
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContract(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContract(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(row.checkStatus == 1){
        this.$alert("合同已审核通过，不允许删除", "提示", { confirmButtonText: "确定", });
        return;
      }else{
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除合同编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delContract(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      }
      
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有合同数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportContract(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 合同下载 */
    contractDownload(item){
      if(null == item.template){
        this.msgError("暂未指定合同模板");
      }else{
        contractDownload({id: item.id, template: item.template}).then(response => {
          let blob = new Blob([response], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          }); // res就是接口返回的文件流了
          let url = window.URL || window.webkitURL;
          let fileURL = url.createObjectURL(blob);
          let a = document.createElement("a");
          a.href = fileURL;
          a.download = item.name + ".doc";
          a.target = "_self";
          a.click();
          url.revokeObjectURL(fileURL);
        });
      }
    }
  }
};
</script>
